<%--
  Created by IntelliJ IDEA.
  User: wsl
  Date: 2021/10/12
  Time: 23:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script typet="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
        //原生JS方式发送 Ajax请求
        function run() {
            //1.核心对象
            var xmlhttp;

            //2.判断浏览器类型
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            //3.建立连接
            xmlhttp.open("GET","/login?username=tom",true);

            //4.发送请求
            xmlhttp.send();

            //5.获取响应结果
            xmlhttp.onreadystatechange=function() {

                //readyState==4 请求已完成，且响应已就绪
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                   var text =xmlhttp.responseText;
                   alert("响应结果: " + text);
                }
            }
        }

        //2.JQuery GET方式
        function run2() {
            //1.url
            var url = "/login";

            //2.数据
            var data = {username:"jack"};

            //3.发送GET请求
            $.get(url,data,function (param) {
               alert("GET异步请求 响应成功 "+ param);
            },"text");
        }

        //3.JQuery POST方式
        function run3() {
            //1.URL
            var url = "/login";

            //2.数据
            var data = {username: "mary"};

            //3.发送 POST请求
            $.post(url,data,function (param) {
              alert("POST异步请求 响应成功 "+ param);
            },"text");
        }

        //4.JQuery Ajax方式
        function run4() {
            $.ajax({
                url:"/login",
                data:{username:"lucy"},
                async:true, //是否异步
                type:"POST", //请求方式
                dataType:"text", //返回数据的数据类型
                success:function (param) {
                    alert("响应成功！"+ param);
                },
                error:function () {
                    alert("响应失败！");
                }
            });
        }

    </script>
</head>
<body>
<input type="button" value="原生JS发送异步请求" onclick="run()"><br>
    局部刷新 <input type="text"><br>
<input type="button" value="JQuery GET方式发送异步请求" onclick="run2()"><br>

<input type="button" value="JQuery POST方式发送异步请求" onclick="run3()"><br>

<input type="button" value="JQuery Ajax方式发送异步请求" onclick="run4()"><br>

</body>
</html>
